Ninja Database Pro supports global triggers, type specific triggers, and also inherited types triggers for interfaces and base classes. Triggers can be used to set default values or perform other logic. Default values can also be set using Database Constraints. It should be noted that Ninja Database Pro will automatically set properties named CreateDate and UpdateDate on save. See Class Setup.
public class BeforeUpdateTrigger : ITrigger { public TriggerAction TriggerAction { get { return TriggerAction.BeforeUpdate; } } public Type TriggerType { get { return typeof(Person); } } public void ExecuteTrigger(Type type, object instance) { Person person = (Person)instance; if (person.Name == "Secret Agent Charlie") { person.Name = "Charlie Smith"; Console.WriteLine("Name Replaced"); } } } public class AfterInsertTrigger : ITrigger { public TriggerAction TriggerAction { get { return TriggerAction.AfterInsert; } } public Type TriggerType { get { return typeof(Person); } } public void ExecuteTrigger(Type type, object instance) { Person person = (Person) instance; Console.WriteLine("Person was inserted with an ID of {0}",person.PersonId); } } [Test] public void TriggerUsageTest() { NinjaDbPro db = new NinjaDbPro("MyDatabaseDirectory", "MyDatabaseName"); db.OpenDatabase(); db.Triggers.Add(new AfterInsertTrigger()); db.Triggers.Add(new BeforeUpdateTrigger()); Person person = new Person(); person.Name = "John Smith"; //The Insert Trigger Will Be Fired Here db.Save(person); //The Before Update Trigger Will Be Fired Here person.Name = "Secret Agent Charlie"; db.Save(person); Console.WriteLine("Person Name is now: {0}", person.Name); db.CloseDatabase(); } |